import React, { useRef, useEffect, useState } from 'react';
import jwt from 'jsonwebtoken';
import { useDispatch } from 'react-redux';

import './index.less';
import Button from '@c/button/Button.tsx';
import Toast from '@c/toast/Toast.tsx';

import reuqest, { postLogin, postEmailCode } from '@/utils/api';
import local from '@/utils/local';
import { valideEmail } from '@/utils/public';
import { setUser } from '@/redux/actions';

interface Props {
  [propName: string]: any;
}
export default function Login(props: Props) {
  const page: any = useRef({
    timer: null,
    codeTime: 59,
  }); // 页面数据
  const canvas: any = useRef({}); // 画布
  const [eye, setEye] = useState(false); // 切换查看密码
  const [loginType, setLoginType] = useState('code'); // 切换验证码登录还是密码登录
  const [loginForm, setLoginForm] = useState({ username: '', password: '', code: '' }); // 登录上传参数

  const [codeContent, setCodeContent] = useState('获取验证码'); // 登录上传参数

  const dispatch = useDispatch();

  // 初始化画布
  const getCurve = (flag: boolean) => {
    const ctx = canvas.current.getContext('2d');
    const ctxHeight = canvas.current.clientHeight;
    const ctxWidth = canvas.current.clientWidth;

    interface drawParams {
      x: number;
      y: number;
      radian: number;
      disRadian: number;
      height: number;
      dis: number;
      acyiveHeight: number;
    }
    function draw(obj: drawParams) {
      let { x, y, radian, disRadian, height, dis, acyiveHeight } = obj;
      function moveSin() {
        radian += 0.1;
        x = radian * dis - dis - 10;
        if (x > ctxWidth) {
          return true;
        }
        y = Math.sin(radian + disRadian) * acyiveHeight + height;

        ctx.lineTo(x, y);
        ctx.stroke();

        return false;
      }

      radian += 0.1;
      x = radian * dis - dis - 10;
      const originX = x;
      y = Math.sin(radian + disRadian) * acyiveHeight + height;
      const originY = y;
      ctx.beginPath();
      ctx.moveTo(x, y);
      ctx.strokeStyle = 'transparent';

      for (let i = 0; i < 1000; i++) {
        let flag = moveSin();
        if (flag) {
          break;
        }
      }
      ctx.lineTo(x, ctxHeight);
      ctx.lineTo(originX, ctxHeight);
      ctx.lineTo(originX, originY);

      ctx.closePath();
      ctx.fillStyle = 'rgba(22,141,197,0.4)';
      ctx.fill();
    }

    let disRadian1 = 0.01;
    let disRadian2 = 5;
    let disRadian3 = 5;

    const loop = () => {
      if (!flag) {
        return;
      }
      ctx.clearRect(0, 0, ctxWidth, ctxHeight);
      disRadian1 += 0.03;
      disRadian2 += 0.05;
      disRadian3 += 0.07;
      draw({ x: 0, y: 0, radian: 1, disRadian: disRadian1, height: 50, dis: 45, acyiveHeight: 20 });
      draw({ x: 0, y: 0, radian: 1, disRadian: disRadian2, height: 45, dis: 43, acyiveHeight: 30 });
      draw({ x: 0, y: 0, radian: 1, disRadian: disRadian3, height: 60, dis: 41, acyiveHeight: 20 });
      requestAnimationFrame(loop);
    };
    loop();
  };

  // 点击登录
  const login = () => {
    if (!loginForm.username.trim()) {
      Toast({ text: '请输入账号', type: 'error' });
      return;
    }
    if (loginType === 'password' && !loginForm.password.trim()) {
      Toast({ text: '请输入密码', type: 'error' });
      return;
    }
    if (loginType === 'code' && !loginForm.code.trim()) {
      Toast({ text: '请输入验证码', type: 'error' });
      return;
    }
    interface _Form {
      username: string;
      password?: string;
      code?: string;
    }
    const _form: _Form = {
      username: loginForm.username,
    };
    // 如果是密码登录
    if (loginType === 'password') {
      _form.password = loginForm.password;
    }
    // 如果是验证码登录
    if (loginType === 'code') {
      _form.password = loginForm.code;
    }
    reuqest.post({ url: postLogin, data: _form }).then((res: any) => {
      console.log('登录结果', res);
      if (res.code === 1) {
        jwt.verify(res.data.token, 'hl', (err: any, data: any) => {
          if (err || !data) {
            // console.log(props);
            Toast({ type: 'error', text: '登录验证错误' });
          } else {
            local.set('token', res.data.token);
            props.router.replace('/home/index');
            dispatch(setUser(data));
          }
        });
      }
    });
  };

  // 切换验证码登录还是密码登录
  const toggleLoginType = () => {
    //如果是密码就切换验证码
    if (loginType === 'password') {
      setLoginType('code');
      return;
    }
    //如果是验证码就切换密码
    if (loginType === 'code') {
      setLoginType('password');
      return;
    }
  };

  // 获取验证码
  const getCode = () => {
    if (!loginForm.username.trim()) {
      Toast({ text: '请输入账号', type: 'error' });
      return;
    }
    if (!valideEmail(loginForm.username)) {
      Toast({ text: '邮箱不正确', type: 'error' });
      return;
    }
    // 设置定时60秒
    const _timer = () => {
      setCodeContent(`${page.current.codeTime}`); //
      page.current.timer = setTimeout(() => {
        // console.log(codeContent);
        if (page.current.codeTime > 0) {
          page.current.codeTime--;
          _timer();
        } else {
          clearTimeout(page.current.timer);
          setCodeContent('获取验证码');
          page.current.codeTime = 59;
        }
      }, 1000);
    };
    _timer();

    reuqest.post({ url: postEmailCode, data: { email: loginForm.username } }).then((res: any) => {
      console.log('验证码', res);
    });
  };

  // 修改登录参数
  const editLoginForm = (e: React.ChangeEvent<HTMLInputElement>, prop: string) => {
    setLoginForm({ ...loginForm, [prop]: e.target.value });
  };

  useEffect(() => {
    getCurve(true); // 初始化曲线
    return () => {
      getCurve(false); // 关闭曲线动画
      clearTimeout(page.current.timer);
    };
  }, []);

  return (
    <div className="login fx fx-d fx-jc-sb">
      <div className="fx0">
        {/* 头像 */}
        <div className="avatar-box"></div>

        {/* 登录 */}
        {/* 用户名 */}
        <div className="input-box fx fx-ai-c">
          <svg className="icon" aria-hidden="true">
            <use xlinkHref="#iconyonghu"></use>
          </svg>
          <input className="input" type="text" placeholder="用户名/QQ邮箱" onChange={e => editLoginForm(e, 'username')} />
        </div>
        {/* 密码 */}
        {loginType === 'password' && (
          <div className="input-box fx fx-ai-c">
            <svg className="icon fx0" aria-hidden="true">
              <use xlinkHref="#icondrxx04"></use>
            </svg>
            <input className={`input ${eye ? '' : 'password'}`} type="text" placeholder="请输入密码" onChange={e => editLoginForm(e, 'password')} />
            {/* 小眼睛 */}
            <i onClick={() => setEye(!eye)} className={`iconfont eye ${eye ? 'iconyanjing-zhengyan' : 'iconyanjing-biyan'}`}></i>
          </div>
        )}

        {/* 验证码 */}
        {loginType === 'code' && (
          <div className="input-box fx fx-ai-c">
            <svg className="icon fx0" aria-hidden="true">
              <use xlinkHref="#icondrxx04"></use>
            </svg>
            <input className={`input ${eye ? '' : 'password'}`} type="text" placeholder="请输入验证码" onChange={e => editLoginForm(e, 'code')} />
            <Button className=" fx0" onClick={getCode} gray={!Number.isNaN(parseInt(codeContent))}>
              {codeContent}
            </Button>
          </div>
        )}

        {/* 按钮 */}
        <Button className="login-btn" onClick={login}>
          登 录
        </Button>

        {/*  */}
        <div className="fx fx-jc-sb register">
          <span onClick={toggleLoginType}>{loginType === 'password' ? '验证码登录' : '密码登录'}</span>
          <p>
            <span style={{ marginRight: '0.2rem' }}>忘记密码</span>
            <span>新用户注册</span>
          </p>
        </div>
      </div>

      {/* 曲线动画 */}
      <div className="curve">
        <canvas ref={canvas} id="canvas" style={{ width: '100%', height: '100%' }}></canvas>
      </div>
    </div>
  );
}
